package com.hpsk.shopsatoken.aspect;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hpsk.common.CommonException;
import com.hpsk.thread.ThreadLocalTestId;
import com.hpsk.thread.ThreadLocalTokenId;
import com.hpsk.utils.CommonServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Slf4j
@Component
public class ThreadLocalAspect {

//    @Pointcut("execution(public * com.hpsk.*.controller..*.*(..)) " +
//            "&& !execution(public * com.hpsk.webSocket.controller..*.*(..))")
//    @Pointcut("@annotation(com.hpsk.annotations.ThreadAspectAnnotation)")
//    public void controllers() {
//    }

    @Pointcut("execution(public * com.hpsk.*.*.*.controller.*.*(..))")
    public void controllers() {
    }

    @Before("controllers()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            if (ObjectUtil.isEmpty(ThreadLocalTokenId.get())) {
//                SaSession tokenInfo = StpUtil.getTokenSession();
                ThreadLocalTokenId.set(StpUtil.getLoginIdAsString());
            }
        } catch (Exception e) {
            if (e instanceof CommonException) {
                throw (CommonException) e;
            }
            log.error("ThreadLocalAspect.doBefore error", e);
        }
    }

    @After("controllers()")
    public void doAfter(JoinPoint joinPoint) {
        removeThreadLocal();
    }

    @AfterThrowing("controllers()")
    public void deAfterThrowing(JoinPoint joinPoint) {
        removeThreadLocal();
    }

    public void removeThreadLocal() {

        if (ObjectUtil.isNotEmpty(ThreadLocalTestId.get())) {
            ThreadLocalTestId.remove();
        }
        if (ObjectUtil.isNotEmpty(ThreadLocalTokenId.get())) {
            ThreadLocalTokenId.remove();
        }
    }
}
